package com.demo.task.utils

import android.annotation.SuppressLint
import android.os.Build

internal object WebViewUtils {
    @SuppressLint("PrivateApi", "DiscouragedPrivateApi")
    fun hookWebView() {
        val sdkInt = Build.VERSION.SDK_INT
        try {
            val factoryClass = Class.forName("android.webkit.WebViewFactory")
            val field = factoryClass.getDeclaredField("sProviderInstance")
            field.isAccessible = true
            var sProviderInstance = field[null]
            if (sProviderInstance != null) {
                return
            }
            val getProviderClassMethod = if (sdkInt > 22) {
                factoryClass.getDeclaredMethod("getProviderClass")
            } else if (sdkInt == 22) {
                factoryClass.getDeclaredMethod("getFactoryClass")
            } else {
                return
            }
            getProviderClassMethod.isAccessible = true
            val providerClass = getProviderClassMethod.invoke(factoryClass) as Class<*>
            val delegateClass = Class.forName("android.webkit.WebViewDelegate")
            val providerConstructor = providerClass.getConstructor(delegateClass)
            providerConstructor.isAccessible = true
            val declaredConstructor = delegateClass.getDeclaredConstructor()
            declaredConstructor.isAccessible = true
            sProviderInstance = providerConstructor.newInstance(declaredConstructor.newInstance())
            field["sProviderInstance"] = sProviderInstance
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }
}